// 移除未使用的导入

interface NetworkConnection {
  effectiveType?: string;
  downlink?: number;
  rtt?: number;
  saveData?: boolean;
}

interface DeviceInfoExtended {
  name: string;
  type: 'mobile';
  platform: string;
  userAgent: string;
  language: string;
  languages: readonly string[];
  online: boolean;
  cookieEnabled: boolean;
  screen: {
    width: number;
    height: number;
    colorDepth: number;
    pixelDepth: number;
  };
  viewport: {
    width: number;
    height: number;
  };
  timezone: string;
  timestamp: string;
  connection?: NetworkConnection;
}

interface DeviceCapabilities {
  speechRecognition: boolean;
  mediaRecording: boolean;
  camera: boolean;
  microphone: boolean;
  geolocation: boolean;
  notifications: boolean;
  vibration: boolean;
  fullscreen: boolean;
  clipboard: boolean;
  share: boolean;
}

interface PermissionStatus {
  microphone: boolean;
  camera: boolean;
  notifications: boolean;
  geolocation: boolean;
}

interface NetworkStatus {
  online: boolean;
  effectiveType: string;
  downlink: number;
  rtt: number;
  saveData: boolean;
}

// 扩展Navigator接口以包含connection属性
declare global {
  interface Navigator {
    connection?: {
      effectiveType: string;
      downlink: number;
      rtt: number;
      saveData: boolean;
    };
    mozConnection?: any;
    webkitConnection?: any;
  }
}

/**
 * 生成唯一设备ID
 */
export function generateDeviceId(): string {
  const timestamp = Date.now().toString(36)
  const random = Math.random().toString(36).substr(2, 9)
  return `mobile_${timestamp}_${random}`
}

/**
 * 获取设备信息
 */
export async function getDeviceInfo(): Promise<DeviceInfoExtended> {
  const info = {
    name: getDeviceName(),
    type: 'mobile',
    platform: navigator.platform,
    userAgent: navigator.userAgent,
    language: navigator.language,
    languages: navigator.languages,
    online: navigator.onLine,
    cookieEnabled: navigator.cookieEnabled,
    screen: {
      width: screen.width,
      height: screen.height,
      colorDepth: screen.colorDepth,
      pixelDepth: screen.pixelDepth
    },
    viewport: {
      width: window.innerWidth,
      height: window.innerHeight
    },
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    timestamp: new Date().toISOString()
  }

  // 获取网络信息（如果支持）
  if ('connection' in navigator && navigator.connection) {
    (info as any).connection = {
      effectiveType: navigator.connection.effectiveType,
      downlink: navigator.connection.downlink,
      rtt: navigator.connection.rtt,
      saveData: navigator.connection.saveData
    }
  }

  return info as DeviceInfoExtended
}

/**
 * 获取设备名称
 */
function getDeviceName(): string {
  const userAgent = navigator.userAgent

  // iOS设备
  if (/iPad/.test(userAgent)) {
    return 'iPad'
  }
  if (/iPhone/.test(userAgent)) {
    return 'iPhone'
  }
  if (/iPod/.test(userAgent)) {
    return 'iPod'
  }

  // Android设备
  if (/Android/.test(userAgent)) {
    const match = userAgent.match(/Android\s([0-9\.]+)/)
    const version = match ? match[1] : ''
    return `Android ${version}`.trim()
  }

  // Windows Phone
  if (/Windows Phone/.test(userAgent)) {
    return 'Windows Phone'
  }

  // 其他移动设备
  if (/Mobile/.test(userAgent)) {
    return 'Mobile Device'
  }

  // 桌面浏览器
  if (/Chrome/.test(userAgent)) {
    return 'Chrome Browser'
  }
  if (/Firefox/.test(userAgent)) {
    return 'Firefox Browser'
  }
  if (/Safari/.test(userAgent) && !/Chrome/.test(userAgent)) {
    return 'Safari Browser'
  }
  if (/Edge/.test(userAgent)) {
    return 'Edge Browser'
  }

  return 'Unknown Device'
}

/**
 * 检测是否为移动设备
 */
export function isMobileDevice(): boolean {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}

/**
 * 检测是否为iOS设备
 */
export function isIOSDevice(): boolean {
  return /iPad|iPhone|iPod/.test(navigator.userAgent)
}

/**
 * 检测是否为Android设备
 */
export function isAndroidDevice(): boolean {
  return /Android/.test(navigator.userAgent)
}

/**
 * 检测是否支持触摸
 */
export function isTouchDevice(): boolean {
  return 'ontouchstart' in window || navigator.maxTouchPoints > 0
}

/**
 * 检测是否为PWA模式
 */
export function isPWAMode(): boolean {
  return window.matchMedia('(display-mode: standalone)').matches ||
         (window.navigator as any).standalone === true
}

/**
 * 获取设备方向
 */
export function getDeviceOrientation(): string {
  if (screen.orientation) {
    return screen.orientation.type
  }

  // 备用方法
  if (window.innerHeight > window.innerWidth) {
    return 'portrait-primary'
  } else {
    return 'landscape-primary'
  }
}

/**
 * 检测网络状态
 */
export function getNetworkStatus(): NetworkStatus {
  const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection

  return {
    online: navigator.onLine,
    effectiveType: connection?.effectiveType || 'unknown',
    downlink: connection?.downlink || 0,
    rtt: connection?.rtt || 0,
    saveData: connection?.saveData || false
  }
}

/**
 * 震动反馈
 */
export function vibrate(pattern: number | number[] = 100): void {
  if ('vibrate' in navigator) {
    navigator.vibrate(pattern)
  }
}

/**
 * 设备ID持久化存储键名
 */
const DEVICE_ID_KEY = 'smartinput_device_id';
const DEVICE_ID_BACKUP_KEY = 'smartinput_device_id_backup';
const DEVICE_FINGERPRINT_KEY = 'smartinput_device_fingerprint';

/**
 * 获取或创建唯一的设备ID（只查本地，不生成）
 */
export function getLocalDeviceId(): string | null {
  // 优先从主存储获取
  let deviceId = localStorage.getItem(DEVICE_ID_KEY);
  
  // 主存储没有，尝试从备份存储获取
  if (!deviceId) {
    deviceId = localStorage.getItem(DEVICE_ID_BACKUP_KEY);
    if (deviceId) {
      // 恢复主存储
      localStorage.setItem(DEVICE_ID_KEY, deviceId);
      console.log('🔄 从备份存储恢复设备ID:', deviceId);
    }
  }
  
  return deviceId;
}

/**
 * 保存设备ID到本地（多级存储）
 */
export function saveDeviceId(id: string) {
  // 主存储
  localStorage.setItem(DEVICE_ID_KEY, id);
  // 备份存储
  localStorage.setItem(DEVICE_ID_BACKUP_KEY, id);
  console.log('💾 设备ID已保存到主存储和备份存储:', id);
}

/**
 * 保存硬件指纹到本地
 */
export function saveDeviceFingerprint(fingerprint: string) {
  localStorage.setItem(DEVICE_FINGERPRINT_KEY, fingerprint);
  console.log('💾 硬件指纹已保存:', fingerprint);
}

/**
 * 获取本地保存的硬件指纹
 */
export function getLocalDeviceFingerprint(): string | null {
  return localStorage.getItem(DEVICE_FINGERPRINT_KEY);
}

/**
 * 验证设备ID的有效性
 */
export function validateDeviceId(deviceId: string): boolean {
  // 检查ID格式
  const pattern = /^(mobile|browser|desktop)_[a-z0-9]+_\d+$/;
  return pattern.test(deviceId);
}

/**
 * 生成稳定硬件指纹（只用稳定字段）
 */
export async function generateHardwareFingerprint(): Promise<string> {
  try {
    const features = [
      navigator.platform,
      navigator.hardwareConcurrency || '1',
      (navigator as any).deviceMemory || 'unknown',
      screen.width + 'x' + screen.height,
      navigator.language
    ];
    const fingerprint = features.join('|');
    const hash = await generateSimpleHash(fingerprint);
    console.log('🔍 生成稳定硬件指纹:', { features, hash });
    return hash;
  } catch (error) {
    console.error('❌ 生成稳定硬件指纹失败:', error);
    return Date.now().toString(36);
  }
}

/**
 * 简单哈希函数
 */
async function generateSimpleHash(str: string): Promise<string> {
  try {
    const encoder = new TextEncoder();
    const data = encoder.encode(str);
    const hashBuffer = await crypto.subtle.digest('SHA-256', data);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    return hashArray.map(b => b.toString(36)).join('').substring(0, 16);
  } catch (error) {
    // 备用哈希算法
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash; // 转换为32位整数
    }
    return Math.abs(hash).toString(36).substring(0, 16);
  }
}

/**
 * 通过socket注册获取设备ID并保存（服务端生成ID，增强版本）
 * @param socket socket.io实例
 * @param deviceInfo 设备基本信息（不含deviceId）
 * @returns Promise<string> 服务端分配的deviceId
 */
export async function registerDeviceAndSaveId(socket: any, deviceInfo: any): Promise<string> {
  return new Promise(async (resolve, reject) => {
    try {
      // 首先尝试使用本地保存的硬件指纹
      let hardwareFingerprint = getLocalDeviceFingerprint();
      
      if (!hardwareFingerprint) {
        // 生成新的硬件指纹
        hardwareFingerprint = await generateHardwareFingerprint();
        saveDeviceFingerprint(hardwareFingerprint);
      }
      
      // 发送注册请求，包含硬件指纹
      const registrationData = {
        ...deviceInfo,
        hardwareFingerprint
      };
      
      console.log('📤 发送设备注册请求（包含硬件指纹）:', registrationData);
      
      socket.emit('device:register', registrationData);
      
      const handler = (resp: any) => {
        if (resp.success && resp.deviceId) {
          // 验证返回的ID格式
          if (validateDeviceId(resp.deviceId)) {
            saveDeviceId(resp.deviceId);
            console.log('✅ 服务端分配设备ID:', resp.deviceId);
            resolve(resp.deviceId);
          } else {
            console.error('❌ 服务端返回的ID格式无效:', resp.deviceId);
            reject('服务端返回的ID格式无效');
          }
        } else {
          reject(resp.message || '注册失败');
        }
        socket.off('device:registered', handler);
      };
      
      socket.on('device:registered', handler);
      
      setTimeout(() => {
        socket.off('device:registered', handler);
        reject('注册超时');
      }, 10000);
    } catch (error) {
      reject(error instanceof Error ? error.message : '注册失败');
    }
  });
}

/**
 * 清除设备ID（用于重置设备）
 */
export function clearDeviceId(): void {
  localStorage.removeItem(DEVICE_ID_KEY);
  localStorage.removeItem(DEVICE_ID_BACKUP_KEY);
  localStorage.removeItem(DEVICE_FINGERPRINT_KEY);
  console.log('🗑️ 已清除所有设备ID相关数据');
}

/**
 * 获取当前设备ID（不创建新的）
 */
export function getCurrentDeviceId(): string | null {
  return getLocalDeviceId();
}

/**
 * 检查设备ID是否需要重新注册
 */
export async function shouldReRegisterDevice(): Promise<boolean> {
  const deviceId = getLocalDeviceId();
  const fingerprint = getLocalDeviceFingerprint();
  
  if (!deviceId || !fingerprint) {
    return true; // 缺少ID或指纹，需要重新注册
  }
  
  // 验证ID格式
  if (!validateDeviceId(deviceId)) {
    console.warn('⚠️ 设备ID格式无效，需要重新注册');
    return true;
  }
  
  // 检查硬件指纹是否发生变化
  const currentFingerprint = await generateHardwareFingerprint();
  if (fingerprint !== currentFingerprint) {
    console.warn('⚠️ 硬件指纹发生变化，需要重新注册');
    return true;
  }
  
  return false; // 不需要重新注册
}

/**
 * 检测设备能力
 */
export async function detectDeviceCapabilities(): Promise<DeviceCapabilities> {
  const capabilities = {
    speechRecognition: false,
    mediaRecording: false,
    camera: false,
    microphone: false,
    geolocation: false,
    notifications: false,
    vibration: false,
    fullscreen: false,
    clipboard: false,
    share: false
  }

  try {
    // 语音识别
    capabilities.speechRecognition = 
      'webkitSpeechRecognition' in window || 'SpeechRecognition' in window

    // 媒体录制
    capabilities.mediaRecording = 
      navigator.mediaDevices && 
      typeof navigator.mediaDevices.getUserMedia === 'function'

    // 地理位置
    capabilities.geolocation = 'geolocation' in navigator

    // 通知
    capabilities.notifications = 'Notification' in window

    // 震动
    capabilities.vibration = 'vibrate' in navigator

    // 全屏
    capabilities.fullscreen = 
      document.fullscreenEnabled || 
      (document as any).webkitFullscreenEnabled ||
      (document as any).mozFullScreenEnabled

    // 剪贴板
    capabilities.clipboard = 
      navigator.clipboard && 
      typeof navigator.clipboard.writeText === 'function'

    // 分享
    capabilities.share = 
      navigator.share && 
      typeof navigator.share === 'function'

    // 检测摄像头和麦克风
    if (capabilities.mediaRecording) {
      try {
        const devices = await navigator.mediaDevices.enumerateDevices()
        capabilities.camera = devices.some(device => device.kind === 'videoinput')
        capabilities.microphone = devices.some(device => device.kind === 'audioinput')
      } catch (error) {
        console.warn('无法枚举媒体设备:', error)
      }
    }

  } catch (error) {
    console.error('检测设备能力失败:', error)
  }

  return capabilities
}

/**
 * 请求设备权限
 */
export async function requestPermissions(): Promise<PermissionStatus> {
  const permissions = {
    microphone: false,
    camera: false,
    notifications: false,
    geolocation: false
  }

  try {
    // 麦克风权限
    if (navigator.mediaDevices) {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
        permissions.microphone = true
        stream.getTracks().forEach(track => track.stop())
      } catch (error) {
        console.warn('麦克风权限被拒绝:', error)
      }
    }

    // 通知权限
    if ('Notification' in window) {
      const permission = await Notification.requestPermission()
      permissions.notifications = permission === 'granted'
    }

    // 地理位置权限
    if ('geolocation' in navigator) {
      try {
        await new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(resolve, reject, { timeout: 5000 })
        })
        permissions.geolocation = true
      } catch (error) {
        console.warn('地理位置权限被拒绝:', error)
      }
    }

  } catch (error) {
    console.error('请求权限失败:', error)
  }

  return permissions
}

/**
 * 保存设备信息到本地存储
 */
export function saveDeviceInfo(deviceInfo: DeviceInfoExtended): void {
  try {
    localStorage.setItem('smartinput_device_info', JSON.stringify(deviceInfo))
  } catch (error) {
    console.error('保存设备信息失败:', error)
  }
}

/**
 * 从本地存储加载设备信息
 */
export function loadDeviceInfo(): DeviceInfoExtended | null {
  try {
    const stored = localStorage.getItem('smartinput_device_info')
    return stored ? JSON.parse(stored) : null
  } catch (error) {
    console.error('加载设备信息失败:', error)
    return null
  }
}
